<template>
  <div class="book-management">
    <el-button type="primary" @click="showDialog">添加图书</el-button>

    <el-table :data="books" style="width: 100%" border>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="书名"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="copies" label="库存"></el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="mini"
            @click="deleteBook(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加图书" :visible.sync="dialogVisible" width="30%">
      <el-form :model="newBook" label-width="80px">
        <el-form-item label="书名" required>
          <el-input v-model="newBook.title"></el-input>
        </el-form-item>
        <el-form-item label="作者" required>
          <el-input v-model="newBook.author"></el-input>
        </el-form-item>
        <el-form-item label="库存" required>
          <el-input-number
            v-model="newBook.copies"
            :min="1"
            :max="100"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addBook">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      newBook: {
        title: '',
        author: '',
        copies: 1
      }
    }
  },
  computed: {
    books() {
      return this.$store.state.books
    }
  },
  methods: {
    showDialog() {
      this.dialogVisible = true
      this.newBook = { title: '', author: '', copies: 1 }
    },
    addBook() {
      this.$store.commit('addBook', this.newBook)
      this.dialogVisible = false
    },
    deleteBook(id) {
      this.$confirm('确定删除该图书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('deleteBook', id)
      })
    }
  }
}
</script>

<style scoped>
.book-management {
  padding: 20px;
}
.el-button {
  margin-bottom: 15px;
}
</style>